package com.mcp.mcpserver.config;

import com.mcp.mcpserver.model.DataSourceModel;
import com.mcp.mcpserver.repository.InMemoryDataSourceRepository;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
 * @author zhangxin569
 * @date 2025/8/6
 */
@Configuration
public class DataSourceConfig {

    @Bean(name = "primaryDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean(name = "dynamicDataSource")
    public DataSource dynamicDataSource(
            @Qualifier("primaryDataSource") DataSource primaryDataSource,
            InMemoryDataSourceRepository repository) {

        DynamicDataSource dynamicDataSource = new DynamicDataSource();

        // 设置默认数据源
        dynamicDataSource.setDefaultTargetDataSource(primaryDataSource);

        // 设置所有目标数据源
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("primary", primaryDataSource);

        // 加载配置的数据源
        for (DataSourceModel config : repository.findAll()) {
            targetDataSources.put(config.getName(), createDataSource(config));
        }

        dynamicDataSource.setTargetDataSources(targetDataSources);
        return dynamicDataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(@Qualifier("dynamicDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    private DataSource createDataSource(DataSourceModel config) {
        HikariDataSource ds = new HikariDataSource();
        ds.setDriverClassName(config.getDriverClassName());
        ds.setJdbcUrl(config.getUrl());
        ds.setUsername(config.getUsername());
        ds.setPassword(config.getPassword());
        ds.setMaximumPoolSize(5);
        ds.setMinimumIdle(1);
        ds.setConnectionTimeout(30000);
        return ds;
    }

    private String getDriverClassName(String type) {
        if ("mysql".equalsIgnoreCase(type)) {
            return "com.mysql.cj.jdbc.Driver";
        } else if ("oceanbase".equalsIgnoreCase(type)) {
            return "com.oceanbase.jdbc.Driver";
        }
        throw new IllegalArgumentException("Unsupported database type: " + type);
    }
}